package online.heycm.platform.web.common.filter;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import online.heycm.platform.common.tools.Jackson;
import online.heycm.platform.web.common.filter.wrapper.CacheRequestWrapper;
import org.springframework.util.CollectionUtils;

/**
 * @author heycm
 * @since 2023/12/9 17:12
 */
public class RequestHelper {

    private RequestHelper() {}

    public static byte[] copyBody(HttpServletRequest request) throws IOException {
        InputStream inputStream = request.getInputStream();
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        int contentLength = request.getContentLength();
        byte[] buffer = new byte[contentLength >= 0 ? contentLength : 1024];
        int bytesRead;
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            byteArrayOutputStream.write(buffer, 0, bytesRead);
        }
        return byteArrayOutputStream.toByteArray();
    }

    public static String getParameter(CacheRequestWrapper wrapper) {
        return wrapper.isPost() ? getPostParameterJson(wrapper) : getGetParameterJson(wrapper);
    }

    public static String getPostParameterJson(CacheRequestWrapper wrapper) {
        return Jackson.toJson(getPostParameter(wrapper));
    }

    public static Map<String, String> getPostParameter(CacheRequestWrapper wrapper) {
        if (wrapper.getBody() == null || wrapper.getBody().length == 0) {
            return null;
        }
        Map<String, String> parameter = new HashMap<>();
        Map<String, String> bodyParams = Jackson.toObject(wrapper.getBody(), Map.class);
        Map<String, String> urlParams = getGetParameter(wrapper);
        if (bodyParams != null) {
            parameter.putAll(bodyParams);
        }
        if (urlParams != null) {
            parameter.putAll(urlParams);
        }
        return parameter;
    }

    public static String getGetParameterJson(CacheRequestWrapper wrapper) {
        return Jackson.toJson(getGetParameter(wrapper));
    }

    public static Map<String, String> getGetParameter(CacheRequestWrapper wrapper) {
        Map<String, String[]> parameterMap = wrapper.getParameterMap();
        if (CollectionUtils.isEmpty(parameterMap)) {
            return null;
        }
        Map<String, String> parameter = new HashMap<>(parameterMap.size());
        for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
            String value;
            if (entry.getValue() == null || entry.getValue().length == 0) {
                value = null;
            } else {
                value = entry.getValue()[0];
            }
            parameter.put(entry.getKey(), value);
        }
        return parameter;
    }

}
